package com.zeyi.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeyi.blog.dao.CommentDao;
import com.zeyi.blog.entity.Comment;
import com.zeyi.blog.entity.User;
import com.zeyi.blog.service.ArticleService;
import com.zeyi.blog.service.CommentService;
import com.zeyi.blog.service.UserService;
import com.zeyi.blog.util.EmailUtil;
import com.zeyi.blog.util.TreeUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文章评论表(Comment)表服务实现类
 *
 * @author 黎先森
 * @since 2020-07-31 15:32:09
 */
@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {

    @Resource
    ArticleService articleService;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    UserService userService;

    @Resource
    EmailUtil emailUtil;

    @Override
    public List<Comment> getArticleComments(String articleId) {
        List<Comment> comments = this.baseMapper.getArticleComments(articleId);
        return TreeUtil.getTreeList(null, comments, null);
    }

    @Override
    public void addComment(Comment comment) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        comment.setFromUserId(user.getId());
        this.baseMapper.insert(comment);
        if (comment.getPid() == null) {
            articleService.incCommentsCount(comment.getArticleId(), 1);
        }
        User receiveUser = userService.findById(comment.getToUserId());
        if (receiveUser.getEmail() != null && !receiveUser.getEmail().equals("")) {
            String content;
            if (comment.getPid() == null) {
                content = user.getUsername() + " 评论了你的博客: " + comment.getContent();
            } else {
                content = user.getUsername() + " 回复了你: " + comment.getContent();
            }
            emailUtil.sendEmail(receiveUser.getEmail(), "信息", content);
        }
    }

    @Override
    @Transactional
    public void deleteComments(String articleId, List<String> ids) {
        int counts = this.baseMapper.getTopCommentCounts(ids);
        this.baseMapper.deleteBatchIds(ids);
        if (counts > 0) {
            articleService.incCommentsCount(articleId, counts * (-1));
        }
    }
}